package com.chaoyong.higo.activity;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.entity.StringEntity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.LayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

import com.chaoyong.higo.R;
import com.chaoyong.higo.adapter.SharAdapter;
import com.chaoyong.higo.adapter.SharAdapter.SetOnClickListeners;
import com.chaoyong.higo.base.BaseActivity;
import com.chaoyong.higo.bean.SharBean;
import com.chaoyong.higo.bean.ShowOrderEntity;
import com.chaoyong.higo.utils.Mlog;
import com.chaoyong.higo.utils.Values;
import com.chaoyong.higo.view.TitleView;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
/**
 * 2016.3.2
 * @author 丁晶
 *
 */
public class SharActivity extends BaseActivity {
	@Override
	public int layoutResID() {
		return R.layout.activity_shar;
	}
	private TitleView shar_titleview;
	private Context context;
	private RecyclerView shar_recyclerview;
	private SharAdapter adapter;
	private SwipeRefreshLayout swipeRefreshLayout;
	private LayoutManager mLayoutManager;
	private List<ShowOrderEntity> data;
	private int number = 5;
	private TextView tv_load_more;
	@Override
	public void findView() {
		shar_titleview=(TitleView) findViewById(R.id.shar_titleview);
		shar_recyclerview=(RecyclerView) findViewById(R.id.shar_recyclerview);
		tv_load_more = (TextView) findViewById(R.id.tv_load_more);
		/*swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
		swipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
			
			@Override
			public void onRefresh() {
				// TODO Auto-generated method stub
				showToast("已经刷新！");
				new Thread(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						try {
							Thread.sleep(3000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}){}.start();
				handler.sendEmptyMessage(0);
			}
		});*/
	}
	/*private MyHandler handler = new MyHandler();
	class MyHandler extends Handler{
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				swipeRefreshLayout.setRefreshing(false);
				break;

			default:
				break;
			}
		}
	}*/

	@Override
	public void init() {
		context=this;
		shar_titleview.setTitleText("商品晒单", context.getResources().getColor(R.color.gray_text));
		shar_titleview.setTitleBack(context.getResources().getColor(R.color.white));
		shar_titleview.setLeftImage(R.drawable.back_red);
		shar_titleview.setonLeftClinck(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		sharList();
		
		mLayoutManager = new LinearLayoutManager(context);
		shar_recyclerview.setLayoutManager(mLayoutManager);
		/*shar_recyclerview.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int lastVisibleItem = ((LinearLayoutManager) mLayoutManager).findLastVisibleItemPosition();
                int totalItemCount = mLayoutManager.getItemCount();
                //lastVisibleItem >= totalItemCount - 4 表示剩下4个item自动加载，各位自由选择
                // dy>0 表示向下滑动
                if (lastVisibleItem + 1 == adapter.getItemCount()) {
                    if(isLoadingMore){
                         //Log.d(TAG,"ignore manually update!");
                    } else{
                         loadMore();//这里多线程也要手动控制isLoadingMore
                        isLoadingMore = false;
                    }
                	//showToast("加载更多！");
                	loadMore();
                }
            }
        });*/
		
		shar_recyclerview.setOnScrollListener(new RecyclerView.OnScrollListener(){
		    //用来标记是否正在向最后一个滑动，既是否向右滑动或向下滑动
		    boolean isSlidingToLast = false;
		 
		    @Override
		    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
		        LinearLayoutManager manager = (LinearLayoutManager)recyclerView.getLayoutManager();
		        // 当不滚动时
		        if (newState == RecyclerView.SCROLL_STATE_IDLE) {
		            //获取最后一个完全显示的ItemPosition
		            int lastVisibleItem = manager.findLastCompletelyVisibleItemPosition();
		            int totalItemCount = manager.getItemCount();
		 
		            // 判断是否滚动到底部，并且是向右滚动
		            if (lastVisibleItem == (totalItemCount -1) && isSlidingToLast) {
		                //加载更多功能的代码
		                /*Ln.e("howes right="+manager.findLastCompletelyVisibleItemPosition());
		                Toast.makeText(getActivityContext(),"加载更多",0).show();*/
		            	loadMore();
		            	//showToast(number+"");
		            }
		        }
		    }
		 
		    @Override
		    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
		        super.onScrolled(recyclerView, dx, dy);
		        //dx用来判断横向滑动方向，dy用来判断纵向滑动方向
		        if(dy > 0){
		            //大于0表示，正在向右滚动
		            isSlidingToLast = true;
		        }else{
		            //小于等于0 表示停止或向左滚动
		            isSlidingToLast = false;
		        }
		 
		    }
		});
		
	}

	
	protected void loadMore() {
		// TODO Auto-generated method stub
		HttpUtils utils = new HttpUtils();
		RequestParams param = new RequestParams();
		try {
			JSONObject jsonObject = new JSONObject();
			jsonObject.putOpt("model", "Share");
			jsonObject.putOpt("app", "1");
			jsonObject.putOpt("function", "getAllShares");
			jsonObject.putOpt("code", "5,,id DESC," + number);
			param.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
		} catch (JSONException e1) {
			e1.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		Mlog.d("人气推荐url=", Values.MAIN_RECOMMEND);
		utils.send(HttpMethod.POST, Values.MAIN_RECOMMEND, param,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						showToast("网络请求失败");
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						String result = arg0.result;
						Mlog.d("rerult=", result);
						if (result != null) {
							try {
								JSONObject object = new JSONObject(result);
								if (object.getString("status").equals("1")) {
//									 JSONObject objec=new JSONObject(object.getString("data"));
									Gson gson = new GsonBuilder().create();
									SharBean image = gson.fromJson(
											result,
											new TypeToken<SharBean>() {
											}.getType());
									data.addAll(image.getData().getList());
									//adapter=new SharAdapter(context,image.getData().getList());
//									adapter.HolderClickListener(new SetOnClickListeners() {
//										
//										@Override
//										public void OnClick() {
//											startActivity(new Intent(context,SharDetailActivity.class));
//										}
//									});
									//shar_recyclerview.setAdapter(adapter);
									adapter.notifyDataSetChanged();
									number += 5;
								}else{
									tv_load_more.setVisibility(View.GONE);
									showToast("没有更多晒单");
								}

							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
					}
				});
	}


	private void sharList() {
		HttpUtils utils = new HttpUtils();
		RequestParams param = new RequestParams();
		try {
			JSONObject jsonObject = new JSONObject();
			jsonObject.putOpt("model", "Share");
			jsonObject.putOpt("app", "1");
			jsonObject.putOpt("function", "getAllShares");
			jsonObject.putOpt("code", "5,,id DESC");
			param.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
		} catch (JSONException e1) {
			e1.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		Mlog.d("人气推荐url=", Values.MAIN_RECOMMEND);
		utils.send(HttpMethod.POST, Values.MAIN_RECOMMEND, param,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						showToast("网络请求失败");
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						String result = arg0.result;
						Mlog.d("rerult=", result);
						if (result != null) {
							try {
								JSONObject object = new JSONObject(result);
								if (object.getString("status").equals("1")) {
//									 JSONObject objec=new JSONObject(object.getString("data"));
									JSONObject datajs = object.getJSONObject("data");
									if("null".equals(datajs.getString("list"))){
										Toast.makeText(context, "暂无晒单！", 0).show();
									}else{
										Gson gson = new GsonBuilder().create();
										SharBean image = gson.fromJson(
												result,
												new TypeToken<SharBean>() {
												}.getType());
										data = image.getData().getList();
										adapter=new SharAdapter(context,data);
//									adapter.HolderClickListener(new SetOnClickListeners() {
//										
//										@Override
//										public void OnClick() {
//											startActivity(new Intent(context,SharDetailActivity.class));
//										}
//									});
										shar_recyclerview.setAdapter(adapter);
									}
								}

							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
					}
				});
		
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.shar_titleview:
			finish();
			break;

		default:
			break;
		}
	}
}
